<?php
/**
 * Created by PhpStorm.
 * User: Celebration-Grey
 * Date: 2017/4/14
 * Time: 16:09
 */

namespace Classes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;

class Email
{
    public static function registerEmail($session_id,$email){
        $code = Email::getVerificationCode($session_id,$email);
        $flag = Mail::send('emails.verification',['code'=>$code],function($message) use ($email){
            $message ->to($email)->subject('微博注册通知邮件');
        });
        if($flag){
            return true;
        }
        else{
            return false;
        }
    }

    public static function resetEmail($session_id,$email){
        $mutipledata = [];
        $mutipledata['email'] = $email;
        $mutipledata['php_session_id'] = $session_id;
        $mutipledata['code'] = Common::getRand();
        $flag = Mail::send('emails.reset',['code'=>$mutipledata['code']],function($message) use ($email){
            $message ->to($email)->subject('微博重置密码通知邮件');
        });
        if($flag){
            $mutipledata['code'] = hash('md5',$mutipledata['code']);
            $result = Email::resetRequest($mutipledata);
            if($result){
                return true;
            }
            else{
                return false;
            }
        }else{
            return false;
        }
    }

    public static function verificate($phpsessionid,$code,$email){
        $temporary = DB::table('weibo_temporary');
        $result = $temporary->where('temporary_session','=',$phpsessionid)->where('temporary_code','=',$code)->where('temporary_email','=',$email)->count();
        if($result){
            return true;
        }
        else{
            return false;
        }
    }

    public static function resetVerifiy($data){
        $reset = DB::table('weibo_reset');
        $result = $reset->where('reset_email','=',$data['email'])->where('reset_code','=',$data['code'])->where('reset_session','=',$data['php_session_id'])->count();
        if ($result){
            return true;
        }
        else{
            return false;
        }
    }

    public static function resetDelete($email){
        $reset = DB::table('weibo_reset');
        $reset->where('reset_email','=',$email)->delete();
    }

    private static function getVerificationCode($session_id,$email){
        $code = Common::getRand();
        $temporary = DB::table('weibo_temporary');
        $temporary->where('temporary_session', '=', $session_id)->update(
            ['temporary_code' => $code,'temporary_email' => $email]
        );
        return $code;
    }

    private static function resetRequest($data){
        $reset = DB::table('weibo_reset');
        $result = $reset->insert([
            'reset_email' => $data['email'],
            'reset_code' => $data['code'],
            'reset_session' => $data['php_session_id']
        ]);
        return $result;
    }
}